<?php

class Wol_Mgr
{
    function Wol_Open($pc_mac)
    {
        $ip="255.255.255.255";//ip是局域网广播地址
        $addr_byte = explode(':', $pc_mac);
        $hw_addr = '';
        for ($a = 0; $a < 6; $a++) $hw_addr .= chr(hexdec($addr_byte[$a]));
        $msg = chr(255) . chr(255) . chr(255) . chr(255) . chr(255) . chr(255);
        for ($a = 1; $a <= 16; $a++) $msg .= $hw_addr;
        //使用UDP socket广播消息
        $s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
        if ($s === false) {
            return array('success' => false, 'message' => "create socket fail! error code：" . socket_last_error() . " - " . socket_strerror(socket_last_error()));
        } else {
            socket_bind($s,"0.0.0.0",6688);
            //设置socket的选项，第三个参数设置为SO_REUSEADDR时，在关机短时间内有效
            $opt_ret = socket_set_option($s, SOL_SOCKET, SO_BROADCAST, 1);
            if ($opt_ret < 0) {
                return array('success' => false, 'message' => "set socket option fail :" . socket_strerror(socket_last_error($s)));
            }
            $result = socket_sendto($s, $msg, strlen($msg), 0, $ip, 666);
            if ($result === false) {
                return array('success' => false, 'message' => "send fail :" . socket_strerror(socket_last_error()));
            } else {
                return array('success' => true, 'message' => "发送成功. MAC: " . htmlspecialchars($pc_mac));
            }
            socket_close($s);
        }
    }
}

// 设置响应头
header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['mac']) || empty($_POST['mac'])) {
        echo json_encode(array('success' => false, 'message' => 'MAC地址不能为空'));
        exit;
    }

    $mac = $_POST['mac'];
    $wol_mgr = new Wol_Mgr();
    $result = $wol_mgr->Wol_Open($mac);
    $wol_mgr = null;
    
    echo json_encode($result);
} else {
    echo json_encode(array('success' => false, 'message' => '只支持POST请求'));
}
?>